<template>
  <div>
    <a-card title="讨论组聊天室" class="discuss-container">
      <p>系统：欢迎来到聊天室</p>
      <p v-for="item in discuss_list" :style="{textAlign: item.is_self ? 'right' : 'left'}">
        <span>{{item.nick_name}}：{{item.content}}</span>
      </p>
    </a-card>
    <a-form layout="inline" style="text-align: left;margin-top: 15px;">
      <a-form-item label="想说的话">
        <a-textarea v-model="msg" style="display: inline-block;width:500px;" placeholder="请输入您要发送的内容" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="sendMsg">发送</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
export default {
  name: 'DiscussPage',
  data () {
    return {
      msg: '',
      ws: null,
      discuss_list: [
        {
          user_id: 11,
          nick_name: '用户一号',
          content: '哈喽啊，来快乐的玩耍吧！',
          is_self: false
        },
        {
          user_id: 13,
          nick_name: '用户二号',
          content: '你怕不是个傻子',
          is_self: true
        }
      ]
    }
  },
  created () {

  },
  mounted () {
    var socket = new WebSocket(`ws://localhost:3001`);
    this.ws = socket;
    socket.addEventListener('open', function (event) {
      console.log('socket is open')
    });

    socket.addEventListener('message', (event) => {
      // console.log('Message from server', event.data);
      let msg = JSON.parse(event.data);

      switch(msg.type){
        case 'get_ident':
          socket.send(JSON.stringify({
            type: 'get_ident',
            user_name: 'threejs',
            user_id: 13
          }));
          break;
        case 'broadcast':
          this.discuss_list.push({
            user_id: msg.user_id,
            nick_name: msg.nick_name,
            content: msg.content,
            is_self: msg.user_id == 13
          });
          break;
      }
      // socket.send(JSON.stringify({
      //   user_id: 13,
      //   nick_name: 'threejs',
      //   content: '我进来了哦',
      // }));
    });
  },
  methods: {
    sendMsg () {
      this.ws.send(JSON.stringify({
        type: 'broadcast',
        user_id: 13,
        nick_name: 'threejs',
        content: this.msg,
      }));
    }
  }
}
</script>

<style lang="less">
  .discuss-container{
    width: 1200px;
    height: 500px;
    border-radius: 5px;
    color: #666;
    background-color: #1919190f;
    .ant-card-head{background-color: #fff;}
    .ant-card-body{}
  }
</style>
